﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
using System.Diagnostics;
using Soketprint;
using MCData;
using Serialprint;
using System.IO;
using System.IO.Ports;
using Image_recognition;
using GetData;
using System.Data;
using System.Windows.Forms;
using A.BLL;

namespace WindowsForms01
{
   public class CsPalletizing
    {
        public static int PalletizingCount = 0;
        static A.BLL.newsContent content1 = new newsContent();
         MessageBoxForm MessageBoxform = null;

        /// <summary>
        /// 优衣库/GU码垛队列计数执行一次
        /// </summary>
        public static void YYKGUPalletizingLineUpGoOnce()
        {
            try
            {
                //if (CsPakingData.M_list_Dic_YYKGUPalletizing.Count == 0 || CsPakingData.M_list_Dic_YYKGUPalletizing.Count == 0)
                //{
                //    lock (CSReadPlc.lockScan)
                //    {
                //        CsInitialization.UpdateYYKPalletizingLineUp();
                //        CsInitialization.UpdateGUPalletizingLineUp();
                //    }
                //}
                if (CsPakingData.M_list_Dic_YYKGUPalletizing.ToList().Count > 0)
                {
                    int CurrentPackingNum = int.Parse(CsPakingData.GetYYKGUPalletizing("Quantity"));
                    string Order_No = CsPakingData.GetYYKGUPalletizing("Order_No");
                    string Color_Code = CsPakingData.GetYYKGUPalletizing("Color_Code");
                    string Warehouse = CsPakingData.GetYYKGUPalletizing("Warehouse");
                    string Set_Code = CsPakingData.GetYYKGUPalletizing("Set_Code");
                    string YK_guid = CsPakingData.GetYYKGUPalletizing("YK_guid");
                    if (CsPakingData.M_list_Dic_YYKGUPalletizing.ToList()[0].ToList().Count > 0)
                    {
                        int FinishNum  = UpdateYYKGUPalletizingNumber(YK_guid);//更新数据库计数
                        CsPakingData.M_list_Dic_YYKGUPalletizing.ToList()[0]["FinishPalletizingNum"] = (int.Parse(CsPakingData.GetYYKGUPalletizing("FinishPalletizingNum")) + 1).ToString();
                         int FinishPalletizingNum = int.Parse(CsPakingData.GetYYKGUPalletizing("FinishPalletizingNum"));
                        Cslogfun.WriteToCartornLog(",单号：" + Order_No + ",Set_Code:" + Set_Code + ",Warehouse:" + Warehouse + ",当前完成数量：" + FinishNum.ToString()+",当前设置码垛数量："+ CurrentPackingNum.ToString());
                        if (FinishPalletizingNum == CurrentPackingNum && CurrentPackingNum != 0)
                        {
                            Cslogfun.WriteToCartornLog("当前订单码垛完成" + ",单号：" + Order_No + ",Set_Code:" + Set_Code + ",Warehouse:" + Warehouse + ",完成数量：" + CsPakingData.GetYYKGUPalletizing("FinishPalletizingNum"));
                            Cslogfun.WriteToCartornLog("根据缓存计数删除");
                            //删除已完成的喷码记录
                            DeleteYYKFinishPalletizingLineUpFromSql(CsPakingData.M_list_Dic_YYKGUPalletizing.ToList()[0]);
                            CsPakingData.M_list_Dic_YYKGUPalletizing.Remove(CsPakingData.M_list_Dic_YYKGUPalletizing.ToList()[0]);//删除列队缓存中的本次
                           //重新加载码垛队列
                            CsInitialization.UpdateYYKGUPalletizingLineUp();
                        }
                        else if (FinishNum == CurrentPackingNum && CurrentPackingNum != 0)
                        {
                            Cslogfun.WriteToCartornLog("当前订单码垛完成" + ",单号：" + Order_No + ",Set_Code:" + Set_Code + ",Warehouse:" + Warehouse + ",完成数量：" + CsPakingData.GetYYKGUPalletizing("FinishPalletizingNum"));
                            Cslogfun.WriteToCartornLog("根据数据库计数删除");
                            //删除已完成的喷码记录
                            DeleteYYKFinishPalletizingLineUpFromSql(CsPakingData.M_list_Dic_YYKGUPalletizing.ToList()[0]);
                            CsPakingData.M_list_Dic_YYKGUPalletizing.Remove(CsPakingData.M_list_Dic_YYKGUPalletizing.ToList()[0]);//删除列队缓存中的本次          
                            //重新加载码垛队列
                            CsInitialization.UpdateYYKGUPalletizingLineUp();
                        }
                    }
                }
            }
            catch (Exception err)
            {
                Cslogfun.WriteToLog(err);
                throw new Exception("提示：" + err.Message);
            }
        }
        /// <summary>
        /// 删除优衣库已完成记录队列
        /// </summary>
        /// <param name="dic_"></param>
        public static void DeleteYYKFinishPalletizingLineUpFromSql(Dictionary<string, string> dic_)
        {
            try
            {
                CsFormShow.GoSqlUpdateInsert(string.Format("UPDATE a SET IsEndScan=1 FROM dbo.YYK_GU_Current AS a WHERE EXISTS(SELECT*FROM dbo.YYKMarkingLineUp WHERE  YK_guid='{0}' AND Order_No=a.po AND Warehouse=a.Warehouse AND Set_Code=a.Set_Code) ", dic_["YK_guid"]));
                string sqlstr = "";
                sqlstr = string.Format("DELETE FROM dbo.YYKMarkingLineUp WHERE YK_guid='{0}'", dic_["YK_guid"]);
               CsFormShow.GoSqlUpdateInsert(sqlstr);
                //清除排单表对应数据
                CsFormShow.GoSqlUpdateInsert(string.Format("DELETE FROM dbo.SchedulingTable WHERE po_guid='{0}'", dic_["YK_guid"]));
                CsFormShow.GoSqlUpdateInsert(string.Format("DELETE FROM dbo.PalletizingtypeTable WHERE  po_guid='{0}'", dic_["YK_guid"]));
                //更新扫码队列
                CsGetData.UpdataScanLineUp();//更新扫码队列
                CsInitialization.PowerOnUpdateCurrentScan();//获取当前扫码信息
                //更新最后码垛结束时间
                CsFormShow.GoSqlUpdateInsert(string.Format("UPDATE dbo.YOUYIKUDO SET EndTime ='{0}' WHERE guid='{1}'", DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss") + " " + DateTime.Now.Millisecond.ToString(), dic_["YK_guid"]));
                //更新库存
                CsFormShow.ComputeStock(dic_["YK_guid"]);
            }
            catch (Exception err)
            {
                Cslogfun.WriteToLog(err);
                throw new Exception("提示：" + err.Message);
            }

        }
        /// <summary>
        /// 更新GU/优衣库订单码垛完成计数
        /// </summary>
        /// <param name="packingguid_"></param>
        /// <param name="po_"></param>
        /// <returns></returns>
        public static int UpdateYYKGUPalletizingNumber(string YK_guid_)
        {
            try
            {
                int FinishPalletizingNum = 0;
                CsFormShow.GoSqlUpdateInsert( string.Format("UPDATE a SET finishPalletizingnumber=isnull(finishPalletizingnumber,0)+1 FROM YOUYIKUDO AS a WHERE EXISTS(SELECT*FROM dbo.YOUYIKUDO WHERE  guid='{0}' AND Order_No=a.Order_No AND Warehouse=a.Warehouse AND Set_Code=a.Set_Code)", YK_guid_));
                CsFormShow.GoSqlUpdateInsert(string.Format("UPDATE dbo.YYKMarkingLineUp SET FinishPalletizingNum=isnull(FinishPalletizingNum,0)+1 WHERE YK_guid='{0}'", YK_guid_));
                //清除码垛类型队列
                if (CsPakingData.M_list_Dic_palletizingtype.Count>0)
                {
                    CsFormShow.GoSqlUpdateInsert(string.Format("DELETE FROM dbo.PalletizingtypeTable WHERE guid='{0}'", CsPakingData.GetPalletizingtype("guid")));
                    CsPakingData.M_list_Dic_palletizingtype.Remove(CsPakingData.M_list_Dic_palletizingtype.ToList()[0]);
                }
                //获取完成码垛数量
                 FinishPalletizingNum =int.Parse( CsFormShow.SqlGetVal(string.Format("SELECT * FROM dbo.YYKMarkingLineUp WHERE YK_guid='{0}'", YK_guid_), "FinishPalletizingNum"));
                //string sqlinsert = string.Format("SELECT Order_No,SUM( ISNULL(finishmarknumber,0)) AS finishmarknumber FROM dbo.YOUYIKUDO WHERE Order_No='{0}' GROUP BY Order_No", po_);
                //DataSet ds = content1.Select_nothing(sqlinsert);
                //return ds.Tables[0].Rows[0]["finishmarknumber"].ToString().Trim();
                //return "";
                return FinishPalletizingNum;
            }
            catch (Exception err)
            {
                Cslogfun.WriteToLog(err);
                throw new Exception("提示：" + err.Message);
            }
        }
        /// <summary>
        /// GAP码垛队列计数执行一次
        /// </summary>
        public static void GAPPalletizingLineUpGoOnce()
        {
            try
            {
                //if (CsPakingData.M_list_Dic_GAPPalletizing.Count==0)
                //{
                //    lock (CSReadPlc.lockScan)
                //    {
                //        CsInitialization.UpdateGAPPalletizingLineUp();
                //    }
                //}
                if (CsPakingData.M_list_Dic_GAPPalletizing.ToList().Count > 0)
                {
                    int CurrentPackingNum = int.Parse(CsPakingData.GetGAPPalletizing("CurrentPackingNum"));
                    string po = CsPakingData.GetGAPPalletizing("订单号码");
                    string Poguid = CsPakingData.GetGAPPalletizing("packing_guid");
                    if (CsPakingData.M_list_Dic_GAPPalletizing.ToList()[0].ToList().Count > 0)
                    {
                        int FinishNum =int.Parse(UpdateGAPPalletizingNumber(Poguid));//更新数据库计数
                        CsPakingData.M_list_Dic_GAPPalletizing.ToList()[0]["FinishPalletizingNum"] = (int.Parse(CsPakingData.GetGAPPalletizing("FinishPalletizingNum")) + 1).ToString();
                        int FinishPalletizingNum_Now = int.Parse(CsPakingData.GetGAPPalletizing("FinishPalletizingNum"));
                        int FinishPalletizingNum =int.Parse( CsGetData.GetGAPPalletizingNumber(Poguid));
                        int Poqty = int.Parse(CsPakingData.GetGAPPalletizing("箱数"));
                        Cslogfun.WriteToCartornLog( ",单号：" + po + ",当前码垛完成：" + FinishPalletizingNum_Now.ToString() +",订单共码垛完成："+ FinishPalletizingNum.ToString() + ",当前设置码垛数量：" + CurrentPackingNum.ToString());
                        if (FinishPalletizingNum_Now == CurrentPackingNum && CurrentPackingNum!=0)
                        {
                            Cslogfun.WriteToCartornLog("当前订单码垛结束" + ",单号：" + po + ",当前码垛完成：" + FinishPalletizingNum_Now.ToString());
                            Cslogfun.WriteToCartornLog("根据缓存计数删除订单");
                            //删除已完成的喷码记录
                            DeleteGAPFinishPalletizingLineUpFromSql(CsPakingData.M_list_Dic_GAPPalletizing.ToList()[0]);
                            CsPakingData.M_list_Dic_GAPPalletizing.Remove(CsPakingData.M_list_Dic_GAPPalletizing.ToList()[0]);//删除列队缓存中的本次
                            CsInitialization.UpdateGAPPalletizingLineUp();
                        }
                        else if (FinishPalletizingNum==Poqty && CurrentPackingNum != 0)
                        {
                            Cslogfun.WriteToCartornLog("当前订单码垛结束" + ",单号：" + po + ",当前码垛完成：" + FinishPalletizingNum_Now.ToString());
                            Cslogfun.WriteToCartornLog("根据数据库装箱单计数删除订单");
                            //删除已完成的喷码记录
                            DeleteGAPFinishPalletizingLineUpFromSql(CsPakingData.M_list_Dic_GAPPalletizing.ToList()[0]);
                            CsPakingData.M_list_Dic_GAPPalletizing.Remove(CsPakingData.M_list_Dic_GAPPalletizing.ToList()[0]);//删除列队缓存中的本次
                            CsInitialization.UpdateGAPPalletizingLineUp();
                        }
                        else if (FinishNum == CurrentPackingNum && CurrentPackingNum != 0)
                        {
                            Cslogfun.WriteToCartornLog( "当前订单码垛结束" + ",单号：" + po + ",当前码垛完成：" + FinishPalletizingNum_Now.ToString());
                            Cslogfun.WriteToCartornLog("根据数据库订单队列计数删除订单");
                            //删除已完成的喷码记录
                            DeleteGAPFinishPalletizingLineUpFromSql(CsPakingData.M_list_Dic_GAPPalletizing.ToList()[0]);
                            CsPakingData.M_list_Dic_GAPPalletizing.Remove(CsPakingData.M_list_Dic_GAPPalletizing.ToList()[0]);//删除列队缓存中的本次
                            CsInitialization.UpdateGAPPalletizingLineUp();
                        }
                    }
                }
            }
            catch (Exception err)
            {
                Cslogfun.WriteToLog(err);
                throw new Exception("提示：" + err.Message);
            }
        }
        /// <summary>
        /// 更新GAP订单码垛完成计数
        /// </summary>
        /// <param name="packingguid_"></param>
        /// <param name="po_"></param>
        /// <returns></returns>
        public static string UpdateGAPPalletizingNumber(string packingguid_)
        {
            try
            {
                CsFormShow.GoSqlUpdateInsert(string.Format("UPDATE dbo.PACKING SET finishPalletizingnumber=isnull(finishPalletizingnumber,0)+1 WHERE guid='{0}'", packingguid_));
                CsFormShow.GoSqlUpdateInsert(string.Format("UPDATE dbo.MarkingLineUp SET FinishPalletizingNum=isnull(FinishPalletizingNum,0)+1 WHERE packing_guid='{0}'", packingguid_));
                //清除码垛类型队列
                CsFormShow.GoSqlUpdateInsert(string.Format("DELETE FROM dbo.PalletizingtypeTable WHERE guid='{0}'", CsPakingData.GetPalletizingtype("guid")));
                CsPakingData.M_list_Dic_palletizingtype.Remove(CsPakingData.M_list_Dic_palletizingtype.ToList()[0]);
                //获取完成码垛数量
                string FinishPalletizingNum = CsFormShow.SqlGetVal(string.Format("SELECT * FROM dbo.MarkingLineUp WHERE packing_guid='{0}'", packingguid_), "FinishPalletizingNum");
                return FinishPalletizingNum;
            }
            catch (Exception err)
            {
                Cslogfun.WriteToLog(err);
                throw new Exception("提示：" + err.Message);
            }
        }
        /// <summary>
        /// 删除GAP已完成记录队列
        /// </summary>
        /// <param name="dic_"></param>
        public static void DeleteGAPFinishPalletizingLineUpFromSql(Dictionary<string, string> dic_)
        {
            try
            {
                CsFormShow.GoSqlUpdateInsert(string.Format("UPDATE a SET IsEndScan=1 FROM dbo.GAP_Current AS a WHERE EXISTS(SELECT*FROM dbo.MarkingLineUp WHERE  packing_guid='{0}' AND  订单号码=a.订单号码 AND 从=a.从) ", dic_["packing_guid"]));
                CsFormShow.GoSqlUpdateInsert(string.Format("DELETE FROM dbo.MarkingLineUp WHERE packing_guid='{0}'", dic_["packing_guid"]));
                //清除排单表中的队列
                CsFormShow.GoSqlUpdateInsert(string.Format("DELETE FROM dbo.SchedulingTable WHERE po_guid='{0}'", dic_["packing_guid"]));
                CsFormShow.GoSqlUpdateInsert(string.Format("DELETE FROM dbo.PalletizingtypeTable WHERE po_guid='{0}'", dic_["packing_guid"]));
                //更新扫码队列
                CsGetData.UpdataScanLineUp();//更新扫码队列
                CsInitialization.PowerOnUpdateCurrentScan();//获取当前扫码信息
                //更新最后码垛结束时间
                CsFormShow.GoSqlUpdateInsert(string.Format("UPDATE dbo.PACKING SET EndTime ='{0}' WHERE guid='{1}';", DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss") + " " + DateTime.Now.Millisecond.ToString(), dic_["packing_guid"]));
                //更新库存
                CsFormShow.ComputeStock(dic_["packing_guid"]);
            }
            catch (Exception err)
            {
                Cslogfun.WriteToLog(err);
                throw new Exception("提示：" + err.Message);
            }

        }
        /// <summary>
        /// 加载码垛列队
        /// </summary>
        /// <param name="dr"></param>
        public static void SetToGAPPalletizing(DataRow dr)
        {
            try
            {
                Dictionary<string, string> DicMarking = new Dictionary<string, string>();
                DicMarking["订单号码"] = dr["订单号码"].ToString().Trim();
                DicMarking["从"] = dr["从"].ToString().Trim();
                DicMarking["到"] = dr["到"].ToString().Trim();
                DicMarking["箱数"] = dr["箱数"].ToString().Trim();
                DicMarking["END"] = "";
                DicMarking["订单号码"] = dr["订单号码"].ToString().Trim();
                DicMarking["Color"] = dr["Color"].ToString().Trim();
                DicMarking["开始序列号"] = dr["开始序列号"].ToString().Trim();
                DicMarking["Carton1"] = "";//上次结束时的喷码计数
                DicMarking["Carton2"] = dr["到"].ToString().Trim();
                // DicMarking["Cartoncount"] = dr["Cartoncount"].ToString().Trim();//上次结束时的喷码计数
                DicMarking["CurrentPackingNum"] = dr["CurrentPackingNum"].ToString().Trim();
                DicMarking["FinishPalletizingNum"] = dr["FinishPalletizingNum"].ToString().Trim();
                DicMarking["packing_guid"] = dr["packing_guid"].ToString().Trim();
                DicMarking["长"] = dr["长"].ToString().Trim();
                DicMarking["宽"] = dr["宽"].ToString().Trim();
                DicMarking["高"] = dr["高"].ToString().Trim();
                DicMarking["外箱代码"] = dr["外箱代码"].ToString().Trim();
                CsPakingData.M_list_Dic_GAPPalletizing.Add(DicMarking);
            }
            catch (Exception err)
            {
                Cslogfun.WriteToLog(err);
                throw new Exception("提示：" + err.Message);
            }

        }
    }
}
